package com.example.ccj.b.a;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.CoordinateConverter;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.UiSettings;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.CameraPosition;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.MarkerOptions;
import com.example.ccj.R;
import com.example.ccj.u.map.LocationUtil;
import com.example.ccj.u.LogUtils;
import com.example.ccj.u.PermissionUtils;
import com.example.ccj.u.ToastUtils;

import java.util.List;


/**
 * 地图单点定位
 */
public class OneMarkerLocation extends BaseActivity implements LocationSource, AMapLocationListener {
    public static final String TAG = "地图单点定位";

    private MapView mMapView = null;//地图控件
    private AMap aMap;
    private AMapLocationClientOption mLocationOption;
    private UiSettings mUiSettings;
    private AMapLocationClient mlocationClient;
    private LocationSource.OnLocationChangedListener mListener;
    private Button stopLocation;

    String jingdu = "116.67533";
    String weidu = "40.37124";
    String title = "";


    @Override
    public void initData(@Nullable Bundle bundle) {

        if (getIntent().getExtras() != null) {
            if (getIntent().getExtras().containsKey("jingdu")) jingdu = this.getIntent().getExtras().getString("jingdu");
            if (getIntent().getExtras().containsKey("weidu")) weidu = this.getIntent().getExtras().getString("weidu");
            if (getIntent().getExtras().containsKey("title")) title = this.getIntent().getExtras().getString("title");
        }

        //申请地图的权限
        PermissionUtils.permission(//网络定位
                Manifest.permission.ACCESS_COARSE_LOCATION,
                //GPS定位
                Manifest.permission.ACCESS_FINE_LOCATION,
                //网络定位
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.CHANGE_WIFI_STATE,
                Manifest.permission.INTERNET,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_LOCATION_EXTRA_COMMANDS,
                //室内定位
                Manifest.permission.BLUETOOTH,
                //室内定位
                Manifest.permission.BLUETOOTH_ADMIN).callback(new PermissionUtils.FullCallback() {
            @Override
            public void onGranted(@NonNull List<String> granted) {

                stopLocation.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        deactivate();
                        stopLocation.setEnabled(false);
                    }
                });

                //初始化地图控制器对象
                if (aMap == null) {
                    aMap = mMapView.getMap();
                    //添加点
                    addMarkersToMap(jingdu,weidu,title);
                    //初始点坐标及地图级别
//            LatLng latLng = new LatLng(40.37124,116.67533);
//            aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
//                    latLng, 13, 30, 30)));
                    mUiSettings = aMap.getUiSettings();
                    mUiSettings.setScaleControlsEnabled(true);
                    mUiSettings.setZoomControlsEnabled(false);
                    mUiSettings.setCompassEnabled(true);
                    aMap.setLocationSource(OneMarkerLocation.this);// 设置定位监听
                    mUiSettings.setMyLocationButtonEnabled(true);
                }
            }

            @Override
            public void onDenied(@NonNull List<String> deniedForever, @NonNull List<String> denied) {

            }
        }).request();

    }

    @Override
    public void initView(@Nullable Bundle savedInstanceState, @Nullable View contentView) {
        stopLocation = findViewById(R.id.one_marker_stop_location);
        mMapView = findViewById(R.id.one_marker_location);
        //获取地图控件引用
        mMapView.onCreate(savedInstanceState);
    }

    @Override
    public int initContentView() {
        return R.layout.custom_activity_one_marker_location;
    }

    private void addMarkersToMap(String jingdu,String weidu,String title){
        Double latitude = Double.parseDouble(weidu);
//                LogUtil.d("经纬度数据："+latitude+"经纬度");
        Double longitude = Double.parseDouble(jingdu);
//                LogUtil.d("经纬度数据："+longitude+"经纬度");
        if (latitude > 53.55 || latitude <3.86 || longitude>135.05 ||longitude<73.66) {
            LogUtils.d(TAG,"纬度"+latitude+","+"经度"+longitude);
            ToastUtils.showShort("经纬度错误");
            return;
        }
            LatLng latlng1 = new LatLng(latitude,longitude);
            CoordinateConverter converter  = new CoordinateConverter();
            // CoordType.GPS 待转换坐标类型
            converter.from(CoordinateConverter.CoordType.GPS);
            // sourceLatLng待转换坐标点
            converter.coord(latlng1);
            // 执行转换操作
            LatLng desLatLng = converter.convert();

            MarkerOptions markerOption1 = new MarkerOptions().icon(BitmapDescriptorFactory
                    .defaultMarker(BitmapDescriptorFactory.HUE_ROSE))
                    .position(desLatLng)
                    .title(title)
                    .draggable(true);
            aMap.addMarker(markerOption1);

            aMap.moveCamera(CameraUpdateFactory.newCameraPosition(new CameraPosition(
                    desLatLng, 17, 45, 0)));
    }


    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            stopLocation.setEnabled(true);
            try {
                mlocationClient = new AMapLocationClient(this);
            } catch (Exception e) {
                e.printStackTrace();
            }
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式s
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (mListener != null && aMapLocation != null) {
            if (aMapLocation != null
                    && aMapLocation.getErrorCode() == 0) {
                mListener.onLocationChanged(aMapLocation);// 显示系统小蓝点

                double[] GPS1 = LocationUtil.gcj02towgs84(aMapLocation.getLongitude(),aMapLocation.getLatitude());

//                ToastUtil.ShowNowMsg(getApplicationContext(),aMapLocation.getLatitude()+","+aMapLocation.getLongitude()+"\n"
//                        +GPS1[0]+GPS1[1]+"\n"+aMapLocation.getAddress());
            } else {
                String errText = "定位失败," + aMapLocation.getErrorCode()+ ": " + aMapLocation.getErrorInfo();
                Log.e("AmapErr",errText);
            }
        }
    }


    private void requestPermission() {
        // checkSelfPermission() 检测权限
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //TODO 申请存储权限
            ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION,android.Manifest.permission.ACCESS_FINE_LOCATION},
                    PERMISSION_REQUEST_CODE);
        }
    }

    private static final int PERMISSION_REQUEST_CODE = 999;


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            //用户点击了“确定” == grantResults[0] == PackageManager.PERMISSION_GRANTED)
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.i("TAG", "onRequestPermissionsResult granted");
            } else {
                Log.i("TAG", "onRequestPermissionsResult denied");
                // TODO 用户拒绝权限申请，则弹出警示框
                showWaringDialog();
            }
        }
    }



    /**
     * 用户拒绝权限的警示
     */
    private void showWaringDialog() {
        new AlertDialog.Builder(this)
                .setTitle("警告！")
                .setMessage("请前往设置->应用->权限管理->打开存储权限，否则无法正常使用！")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //TODO 一般情况下如果用户不授权的话，功能时无法运行的，则直接退出
                        finish();
                    }
                }).show();
    }


}
